<template>
  <a-drawer
      title="Order Details"
      :open="open"
      @close="handleClose"
      class="order-detail-drawer"
      :bodyStyle="{ padding: '16px', overflowX: 'hidden' }"
      :width="drawerWidth"
      :closable="true"
      placement="right"
  >
    <template v-if="order">
      <a-descriptions title="Order Information" bordered :column="2">
        <a-descriptions-item label="Order Number">{{ order.order_no }}</a-descriptions-item>
        <a-descriptions-item label="Payment Order Number">{{ order.out_trade_no || 'No' }}</a-descriptions-item>

        <a-descriptions-item label="Payment Time"><DateFormatter :value="order.pay_time" format="MM/DD/YYYY HH:mm:ss" fallback="No" /></a-descriptions-item>
        <a-descriptions-item label="Payment Method">{{ order.pay_method || 'No' }}</a-descriptions-item>

        <a-descriptions-item label="Recipient Information" :span="2">
          <div>Name: {{ order.address?.name }}</div>
          <div>Phone: {{ order.address?.phone }}</div>
          <div>Address: {{order.address?.county + order.address?.province + order.address?.city + order.address?.full_address}}</div>
        </a-descriptions-item>

        <a-descriptions-item label="Logistics Information" :span="2" v-if="order.delivery && order.delivery.length > 0">
          <div>Logistics Company: {{ order.delivery[0].delivery_company?.name }}</div>
          <div>Logistics Number: {{ order.delivery[0].delivery_no }}</div>
        </a-descriptions-item>
        <a-descriptions-item label="Logistics Information" :span="2" v-else>No Logistics Information</a-descriptions-item>

        <a-descriptions-item label="Remark" :span="2">{{ order.remark || 'No' }}</a-descriptions-item>
      </a-descriptions>

      <a-divider>
        <a-space>
          <shopping-outlined />
          <span class="divider-title">Product Details</span>
        </a-space>
      </a-divider>

      <div class="product-list-container">
        <a-list
            :dataSource="order.detail"
            bordered
            class="product-list"
        >
          <template #renderItem="{ item }">
            <a-list-item class="product-item">
              <a-list-item-meta class="product-meta">
                <template #avatar>
                  <div class="product-image-container">
                    <img :src="item.image" alt="Product Image" class="product-image"/>
                  </div>
                </template>
                <template #title>
                  <div class="product-name">{{ item.goods_name }}</div>
                </template>
                <template #description>
                  <div class="product-spec">
                    Specification:
                    <template v-if="parseSpecText(item.spec_text).size">
                      {{ parseSpecText(item.spec_text).size }}
                    </template>
                    <template v-if="parseSpecText(item.spec_text).imageUrl">
                      <span class="color-image-container">
                        <img :src="parseSpecText(item.spec_text).imageUrl" alt="Color" class="color-image"/>
                      </span>
                    </template>
                    <template v-if="!parseSpecText(item.spec_text).size && !parseSpecText(item.spec_text).imageUrl">
                      {{ item.spec_text || 'Default Specification' }}
                    </template>
                  </div>
                  <!-- 申请售后按钮 - 显示在待收货、待评价、已完成状态 -->
                  <div class="after-sale-action" v-if="order.status >= 3 && order.status <= 5 && item.apply_refund">
                    <a-button size="small" type="link" @click="handleAfterSale(item)">Apply for after-sales service</a-button>
                  </div>
                </template>
              </a-list-item-meta>
              <div class="product-price-info">
                <div class="price-item">Unit Price: <span class="price-value">{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(item.price) }}</span></div>
                <div class="price-item">Quantity: <span class="quantity">{{ item.num }}</span></div>
                <div class="price-item subtotal">Subtotal: <span class="subtotal-value">{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice((parseFloat(item.price) * item.num)) }}</span></div>
              </div>
            </a-list-item>
          </template>
        </a-list>
      </div>

      <div class="order-total">
        <div class="total-row">Total Price: <span class="total-value">{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(order.total_price) }}</span></div>
        <div class="total-row">Freight: <span class="total-value">{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(order.freight) }}</span></div>
        <div class="total-row">Freight Insurance: <span class="total-value">{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(order.freight_insurance) }}</span></div>
        <div class="total-row">Tariff: <span class="total-value">{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(order.tariff) }}</span></div>
        <div class="total-row" v-if="order.discount_data">Discount: <span class="discount-value">-{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(order.discount_data.coupon_discount) || '0.00' }}</span></div>
        <!--        <div class="total-row">Total Discount: <span class="discount-value">-¥{{ order.total_discount }}</span></div>-->
        <div class="grand-total">Total Order: <span class="grand-total-value">{{ useCurrency.currentCurrency.unit }}{{ proxy.$ConvertPrice(order.pay_price) }}</span></div>
      </div>

      <!-- 订单详情底部操作按钮 -->
      <div class="order-actions">
        <!-- 待付款 -->
        <template v-if="order.status === 1">
          <a-button type="primary" @click="handlePay">Repay</a-button>
          <a-button danger @click="handleCancel">cancellation of order</a-button>
        </template>

        <!-- 待发货 -->
        <template v-if="order.status === 2">
          <a-button @click="handleCancel">cancellation of order</a-button>
          <a-button @click="handleBuyAgain">Buy Again</a-button>
        </template>

        <!-- 待收货 -->
        <template v-if="order.status === 3">
          <a-button type="primary" @click="handleConfirmReceipt">Confirm Receipt</a-button>
          <a-button @click="handleViewLogistics">View Logistics</a-button>
          <a-button @click="handleContactSeller">Contact Seller</a-button>
        </template>

        <!-- 待评价 -->
        <template v-if="order.status === 4">
          <a-button type="primary" @click="handleReview">Return & Exchange</a-button>
        </template>

        <!-- 已完成 -->
        <template v-if="order.status === 5">
          <a-button @click="handleBuyAgain">Buy Again</a-button>
          <a-button danger @click="handleDelete">Delete Order</a-button>
        </template>

        <!-- 已取消 -->
        <template v-if="order.status === 7">
          <a-button @click="handleBuyAgain">Return & Exchange</a-button>
        </template>
      </div>
    </template>
  </a-drawer>

  <!-- 售后弹窗 -->
  <AfterSaleModal
      v-model:open="afterSaleVisible"
      :order="order"
      :item="currentAfterSaleItem"
      @submit="handleAfterSaleSubmit"
  />
</template>

<script setup>
import {ref, watch, onMounted, onBeforeUnmount, computed, getCurrentInstance} from 'vue';
import { ShoppingOutlined } from '@ant-design/icons-vue';
import AfterSaleModal from './AfterSaleModal.vue';
import DateFormatter from "@/components/common/DateFormatter.vue";
import { useCurrencyStore } from '@/store';
const { proxy } = getCurrentInstance();
const useCurrency = useCurrencyStore();
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  order: {
    type: Object,
    default: null
  }
});

const emit = defineEmits(['update:visible', 'pay', 'cancel', 'confirm-receipt', 'view-logistics', 'contact-seller', 'review', 'buy-again', 'delete', 'after-sale', 'after-sale-submit']);

// 解析规格文本
const parseSpecText = (specText) => {
  if (!specText) return { size: '', imageUrl: '' };

  // 检查是否包含图片URL和尺寸
  if (specText.includes('http') && specText.includes('，')) {
    const parts = specText.split('，');
    return {
      imageUrl: parts[0],
      size: parts[1] || ''
    };
  }

  // 检查是否只有图片URL
  if (specText.includes('http')) {
    return {
      imageUrl: specText,
      size: ''
    };
  }

  // 只有尺寸
  return {
    imageUrl: '',
    size: specText
  };
};

// 格式化倒计时
const formatCountdown = (seconds) => {
  if (seconds <= 0) return 'Expired';

  // Maximum payment time is 30 minutes from order creation
  const maxTimeInSeconds = 30 * 60; // 30 minutes in seconds

  // If seconds is greater than the max time, it's already expired
  if (seconds > maxTimeInSeconds) {
    return 'Expired';
  }

  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;

  return `${minutes}m ${remainingSeconds}s`;
};

const handleClose = () => {
  emit('update:visible', false);
};

const handlePay = () => {
  emit('pay', props.order);
};

const handleCancel = () => {
  emit('cancel', props.order);
};

const handleConfirmReceipt = () => {
  emit('confirm-receipt', props.order);
};

const handleViewLogistics = () => {
  emit('view-logistics', props.order);
};

const handleContactSeller = () => {
  emit('contact-seller', props.order);
};

const handleReview = () => {
  emit('review', props.order);
};

const handleBuyAgain = () => {
  emit('buy-again', props.order);
};

const handleDelete = () => {
  emit('delete', props.order);
};

// 售后弹窗
const afterSaleVisible = ref(false);
const currentAfterSaleItem = ref(null);

const handleAfterSale = (item) => {
  currentAfterSaleItem.value = item;
  afterSaleVisible.value = true;
};

// 处理售后提交
const handleAfterSaleSubmit = (data) => {
  emit('after-sale-submit', data);
  afterSaleVisible.value = false;
};

// Add window width tracking
const windowWidth = ref(window.innerWidth);
const drawerWidth = computed(() => {
  if (windowWidth.value <= 576) {
    return '100%';
  } else if (windowWidth.value <= 768) {
    return '85%';
  } else {
    return '600px';
  }
});

// Add window resize handler
const handleResize = () => {
  windowWidth.value = window.innerWidth;
};

onMounted(() => {
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.order-detail-drawer :deep(.ant-descriptions-item-label) {
  font-weight: 500;
  background-color: #fafafa;
}

.divider-title {
  font-size: 16px;
  font-weight: 500;
  color: #000000;
}

.product-list-container {
  margin: 16px 0;
  width: 100%;
}

.product-list {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  width: 100%;
}

.product-item {
  padding: 16px;
  transition: background-color 0.3s;
  display: flex;
  flex-wrap: wrap;
}

.product-item:hover {
  background-color: #f5f5f5;
}

.product-meta {
  flex: 1;
  min-width: 200px;
}

.product-image-container {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.product-image:hover {
  transform: scale(1.05);
}

.product-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
  word-break: break-word;
}

.product-spec {
  color: #666;
  font-size: 13px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.after-sale-action {
  margin-top: 8px;
}

.color-image-container {
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  overflow: hidden;
  margin-left: 8px;
  border: 1px solid #eee;
  vertical-align: middle;
}

.color-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-price-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  min-width: 120px;
  margin-left: auto;
}

.price-item {
  margin-bottom: 6px;
  color: #666;
}

.price-value, .quantity {
  font-weight: 500;
  color: #333;
}

.subtotal {
  font-weight: 500;
}

.subtotal-value {
  color: #ff4d4f;
  font-weight: 600;
}

.order-total {
  margin-top: 24px;
  padding: 16px 20px;
  background: #f9f9f9;
  border-radius: 8px;
  text-align: right;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  width: 100%;
  box-sizing: border-box;
}

.total-row {
  margin-bottom: 8px;
  color: #666;
}

.total-value {
  font-weight: 500;
  color: #333;
  margin-left: 8px;
}

.discount-value {
  font-weight: 500;
  color: #52c41a;
  margin-left: 8px;
}

.grand-total {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px dashed #d9d9d9;
}

.grand-total-value {
  font-size: 20px;
  color: #f5222d;
  margin-left: 8px;
}

.countdown {
  font-size: 14px;
  color: #ff5f3c;
  margin-right: 15px;
  display: flex;
  align-items: center;
}

.order-actions {
  margin-top: 24px;
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.order-actions .ant-btn {
  margin-left: 12px;
}

/* Responsive styles */
@media (max-width: 768px) {
  .order-detail-drawer :deep(.ant-drawer-content-wrapper) {
    width: 100% !important;
  }

  :deep(.ant-descriptions-bordered.ant-descriptions-small .ant-descriptions-item-label,
         .ant-descriptions-bordered.ant-descriptions-small .ant-descriptions-item-content) {
    padding: 8px 12px;
  }

  .product-item {
    flex-direction: column;
    padding: 12px;
  }

  .product-meta {
    margin-bottom: 12px;
    min-width: 100%;
  }

  .product-price-info {
    align-items: flex-start;
    width: 100%;
    margin-left: 0;
    margin-top: 8px;
  }

  .order-actions {
    justify-content: center;
  }

  .order-actions .ant-btn {
    margin: 4px;
  }

  .order-total {
    padding: 12px;
    font-size: 14px;
  }

  .grand-total {
    font-size: 16px;
  }

  .grand-total-value {
    font-size: 18px;
  }
}

@media (max-width: 576px) {
  :deep(.ant-descriptions) {
    overflow-x: auto;
  }

  :deep(.ant-descriptions-bordered .ant-descriptions-view) {
    border: none;
  }

  :deep(.ant-descriptions-bordered .ant-descriptions-row) {
    border-bottom: 1px solid #f0f0f0;
  }

  :deep(.ant-descriptions-item-label),
  :deep(.ant-descriptions-item-content) {
    word-break: break-word;
  }

  .product-image-container {
    width: 60px;
    height: 60px;
  }

  .product-name {
    font-size: 14px;
  }

  .order-actions {
    flex-direction: column;
    align-items: stretch;
  }

  .order-actions .ant-btn {
    margin: 4px 0;
    width: 100%;
  }

  .countdown {
    width: 100%;
    justify-content: center;
    margin-right: 0;
    margin-bottom: 8px;
  }
}

/* Additional drawer styling to ensure the close button is accessible */
:deep(.ant-drawer-header) {
  padding: 16px;
  display: flex;
  align-items: center;
  position: relative;
}

:deep(.ant-drawer-close) {
  position: absolute;
  top: 17px;
  right: 16px;
  padding: 8px;
  margin: 0;
  z-index: 10;
  display: block;
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
}

@media (max-width: 576px) {
  :deep(.ant-drawer-header) {
    padding: 12px 40px 12px 12px;
  }

  :deep(.ant-drawer-title) {
    font-size: 16px;
    width: calc(100% - 30px);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  :deep(.ant-drawer-close) {
    top: 10px;
    right: 10px;
    width: 30px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  :deep(.ant-drawer-body) {
    padding: 12px;
  }
}
</style>
